package com.steven.download;

import android.content.Context;
import android.content.Intent;
import android.text.format.Formatter;
import android.util.Log;

import com.steven.download.download.DownloadCallback;
import com.steven.download.download.DownloadFacade;
import com.steven.download.download.UnZipCallback;
import com.steven.download.download.db.DownloadEntity;
import com.steven.download.download.db.room.AppDataBase;
import com.steven.download.utils.SPUtils;
import com.steven.download.utils.StorageQueryUtil;
import com.steven.download.utils.Utils;
import com.steven.download.utils.ZipFileUtils;
import com.steven.download.widget.CircleProgressbar;
import com.steven.download.widget.recyclerView.CommonRecycleAdapter;
import com.steven.download.widget.recyclerView.CommonViewHolder;

import java.io.File;
import java.util.List;

/**
 * Description:
 * Data：4/11/2019-11:05 AM
 *
 * @author yanzhiwen
 */
public class ZipAdapter extends CommonRecycleAdapter<DownloadEntity> {
    private static final String TAG = ZipAdapter.class.getSimpleName();
    private Context mContext;

    private List<DownloadEntity> mDatas;
    public ZipAdapter(Context context, List<DownloadEntity> mDatas, int layoutId) {
        super(context, mDatas, layoutId);
        this.mDatas = mDatas;
        this.mContext = context;
    }

    @Override
    public void convert(CommonViewHolder holder, DownloadEntity downInfoEntity, int position) {
//        ImageView appIcon = holder.getView(R.id.icon);
//        Glide.with(appIcon.getContext())
//                .load(appEntity.appIcon)
//                .into(appIcon);
        CircleProgressbar progressbar = holder.getView(R.id.pb);

        if (downInfoEntity.downloadStatus == DownloadStatus.IDLE ){
            progressbar.setCurrentProgress(0);
            progressbar.setText("下载");
        }else if (downInfoEntity.downloadStatus == DownloadStatus.DOWNLOADING){
            progressbar.setCurrentProgress(downInfoEntity.getProgress());
        }else if (downInfoEntity.downloadStatus == DownloadStatus.PAUSE){
            progressbar.setText("继续");
        }else if (downInfoEntity.downloadStatus == DownloadStatus.FAIL){
            progressbar.setText("失败");
        }else if (downInfoEntity.downloadStatus == DownloadStatus.SUCCESS){
            progressbar.setCurrentProgress(100);
            progressbar.setText("成功");
        }
        String old = downInfoEntity.getPackageName();
        String name = old.substring(old.lastIndexOf("/")+1,old.lastIndexOf("?"));
        holder.setText(R.id.name, name)
                .setText(R.id.size, "大小:" + downInfoEntity.getPackageSize())
                .setText(R.id.downloadCount, "解压大小:" + downInfoEntity.getPackageFileSize());
        try {
            holder.setText(R.id.size,"大小"+ Formatter.formatFileSize(mContext, Long.valueOf(downInfoEntity.getPackageSize())));
            holder.setText(R.id.downloadCount,"解压大小"+ Formatter.formatFileSize(mContext, Long.valueOf(downInfoEntity.getPackageFileSize())));
        }catch (Exception e){

        }
        progressbar.setOnClickListener(v -> {
            starDown(downInfoEntity,progressbar);
        });
        if (downInfoEntity.downloadStatus != DownloadStatus.SUCCESS && holder.getLayoutPosition() == 0){
            Log.e(TAG,"可利用大小:"+Formatter.formatFileSize(mContext,StorageQueryUtil.getAVailableSize()));
            if (StorageQueryUtil.getAVailableSize() > Long.valueOf(downInfoEntity.getPackageFileSize())){
                starDown(downInfoEntity,progressbar);
            }else {
                Log.e(TAG,"内存不足");
            }
        }
    }


    private void starDown(DownloadEntity downInfoEntity,CircleProgressbar progressbar){
        String old = downInfoEntity.getPackageName();
        String name = old.substring(old.lastIndexOf("/")+1,old.lastIndexOf("?"));
        if (downInfoEntity.downloadStatus == DownloadStatus.IDLE
                || downInfoEntity.downloadStatus == DownloadStatus.PAUSE
                || downInfoEntity.downloadStatus == DownloadStatus.FAIL) {
//                /bookmgrotherdev/LDhlB3RJstJba2HX.211108.182529.install.zip?1636367238426

            DownloadFacade.getFacade().startDownload(downInfoEntity.getPackageUrl(), name,downInfoEntity, new DownloadCallback() {
                @Override
                public void onSuccess(File file) {
                    downInfoEntity.downloadStatus = DownloadStatus.SUCCESS;
                    progressbar.setText("成功");
                    Log.d(TAG, file.getName() + "下载成功："+ file.getAbsolutePath());
                    ZipFileUtils.unzipFile(file.getAbsolutePath(), AppConstant.BOOK_UNZIP_DIR,
                            AppConstant.IMG_UNZIP_DIR, AppConstant.UNINSTALL, new UnZipCallback() {

                                @Override
                                public void onSuccess(String zipPath) {
                                    if (!downInfoEntity.isAvailable()){
                                        Log.e("test:","解压文件："+zipPath);
                                        ZipFileUtils.deleteUnInstalFile(zipPath);
                                    }
                                    AppDataBase.getInstance(Utils.getContext()).getDownloadDao()
                                            .deleteByUrl(downInfoEntity.getPackageUrl());
                                    mDatas.remove(downInfoEntity);
                                    notifyDataSetChanged();
                                    List<DownloadEntity> list =  AppDataBase.getInstance(Utils.getContext()).getDownloadDao().queryAll();
                                    if (list == null || list.size() < 1){
                                        SPUtils.getInstance().put(AppConstant.LAST_SYNC_TIME,Utils.getCreateTimeStr());
                                        Intent instant = new Intent(mContext,MainActivity.class);
                                        mContext.startActivity(instant);
                                    }
                                }

                                @Override
                                public void onFailure(Exception e) {

                                }
                            });
                }

                @Override
                public void onFailure(Exception e) {
                    downInfoEntity.downloadStatus = DownloadStatus.FAIL;
                    progressbar.setText("失败");
                    Log.d(TAG, "下载失败" + e.getMessage());

                }

                @Override
                public void onProgress(long progress, long currentLength, File file) {
//                        Log.d(TAG, currentLength+"_onProgress" + progress);
                    downInfoEntity.downloadStatus = DownloadStatus.DOWNLOADING;
                    progressbar.setCurrentProgress(Utils.keepTwoBit((float) progress / currentLength));
                }

                @Override
                public void onPause(long progress, long currentLength) {
                    downInfoEntity.downloadStatus = DownloadStatus.PAUSE;
                    progressbar.setText("继续");
                }
            });
        } else if (downInfoEntity.downloadStatus == DownloadStatus.DOWNLOADING) {
            DownloadFacade.getFacade().stopDownload(downInfoEntity.getPackageUrl());
        }
    }

}
